package br.com.peri.repository.bean;

import java.util.List;

import javax.persistence.Query;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import br.com.peri.Pessoa;
import br.com.peri.repository.PessoaRepository;

public class PessoaRepositoryBean extends PeriRepositoryBean implements
		PessoaRepository {

	private static final long serialVersionUID = 1L;

	@Override
	public Pessoa getPessoaPorCpfCnpj(String cpfCnpj) {
		Criteria criteria = getSession().createCriteria(Pessoa.class);
		criteria.add(Restrictions.or(Restrictions.eq("cpf", cpfCnpj),
				Restrictions.eq("cnpj", cpfCnpj)));
		@SuppressWarnings("rawtypes")
		List ps = criteria.list();
		return ps.size() > 0 ? (Pessoa) ps.get(0) : null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Pessoa> listarPessos(String nome, String cpf, String cnpj) {
		StringBuilder hql = new StringBuilder(
				"select p from Pessoa p where 1=1");
		if (StringUtils.isNotBlank(nome)) {
			hql.append(" and p.nome like :nome");
		}
		if (StringUtils.isNotBlank(cpf)) {
			hql.append(" and p.cpf like :cpf");
		}
		if (StringUtils.isNotBlank(cnpj)) {
			hql.append(" and p.cnpj like :cnpj");
		}
		Query query = entityManager.createQuery(hql.toString());
		if (StringUtils.isNotBlank(nome)) {
			query.setParameter("nome", nome);
		}
		if (StringUtils.isNotBlank(cpf)) {
			query.setParameter("cpf", cpf);
		}
		if (StringUtils.isNotBlank(cnpj)) {
			query.setParameter("cnpj", cnpj);
		}
		return query.getResultList();
	}

}
